const baseUrl = 'http://localhost:8000';

const http = {
	baseUrl,
	async request(config) {
		config = beforeRequest(config);
		config.url = this.baseUrl + config.url;
		try {
			const res = await uni.request(config);
			return beforeResponse(res);
		} catch (err) {
			errorHandle(err);
			return Promise.reject(err);
		}
	},
	get(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "GET",
			proxy: true,
			noToken,
		});
	},
	put(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "PUT",
			proxy: true,
			noToken,
		});
	},
	post(url, data, noToken, contentType) {
		return this.request({
			contentType: contentType,
			url,
			data,
			method: "POST",
			proxy: true,
			noToken
		});
	},
	delete(url, data, noToken) {
		return this.request({
			url,
			data,
			method: "DELETE",
			proxy: true,
			noToken,
		});
	}
};

//请求拦截器
const beforeRequest = (config) => {
	config.header = {
		"Accept": "application/json", // 接受的数据类型
		"Content-Type": config.contentType ? config.contentType : "application/json",
	};
	return config;
};

// 响应拦截器
const beforeResponse = (response) => {
	if (response[1].statusCode < 300) {
		return response[1].data;
	} else if (response[1].statusCode === 401 || response[1].statusCode === 403) {
		uni.showToast({
			title: "验证码输入错误",
			icon: 'none'
		});
		uni.redirectTo({
			url: '/pages/login/login'
		});
		return Promise.reject(new Error("Unauthorized"));
	} else {
		if (typeof response[1].data === "string") {
			uni.showToast({
				title: '服务器或网络错误,请稍后重试',
				icon: "none",
			});
		} else {
			return Promise.reject({
				status: response[1].statusCode,
				error: response[1].data.error || response[1].data.detail
			});
		}
	}
};

const errorHandle = (err) => {
	console.log(err);
	uni.showToast({
		title: '服务器或网络错误,请稍后重试',
		icon: "none",
	});
};

export default http;